﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Process.BLL;
using Process.Entities;
using System.Text.RegularExpressions;
using System.Data;
using KZ.Utilities;
using Process;

namespace Business.Administrator
{
    public partial class Transaction : System.Web.UI.Page
    {
        Regex regex = new Regex(@"(.*)(\?op\=)(.*)");

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadProvider();
            }
        }

        protected void ddlProvider_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlProvider.SelectedIndex == 0)
            {
                ddlCategory.DataSource = null;
                ddlCategory.DataBind();
            }
            else
            {
                string providerID = ddlProvider.SelectedValue;
                ProviderENT provider = ProviderBLL.GetProviderByID(providerID);

                LoadCategory(provider.WS2);
                LoadProduct(provider.WS3, String.Empty);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string providerID = ddlProvider.SelectedValue;
            ProviderENT provider = ProviderBLL.GetProviderByID(providerID);

            LoadProduct(provider.WS3, ddlCategory.SelectedValue);
        }

        protected void btnRegisterTrans_Click(object sender, EventArgs e)
        {
            List<TransactionENT> transList = new List<TransactionENT>();
            CheckBox chk = new CheckBox();
            foreach (GridViewRow row in dtgProduct.Rows)
            {
                chk = row.FindControl("chkSelect") as CheckBox;
                if (chk != null && chk.Checked)
                {
                    string productID = Utility.StringParse(dtgProduct.DataKeys[row.RowIndex].Value);
                    transList.Add(new TransactionENT
                    {
                        TransID = Guid.NewGuid().ToString(),
                        ProviderID = ddlProvider.SelectedValue,
                        ProductID = Utility.StringParse(dtgProduct.DataKeys[row.RowIndex].Value),
                        MinQuantity = Utility.IntParse((row.Cells[4].FindControl("txtMinQuantity") as TextBox).Text),
                        NextTransQuantity = Utility.IntParse((row.Cells[5].FindControl("txtNextTransQuantity") as TextBox).Text),
                        BeginTransDate = Utility.DateTimeParse((row.Cells[7].FindControl("txtBeginTransDate") as TextBox).Text, Global.Culture),
                        EndTransDate = Utility.DateTimeParse((row.Cells[8].FindControl("txtEndTransDate") as TextBox).Text, Global.Culture),
                        TransStatus = TransStatus.Draft.ToString()
                    });
                }
            }

            string providerID = ddlProvider.SelectedValue;
            ProviderENT provider = ProviderBLL.GetProviderByID(providerID);

            RegisterTrans(provider.WS4, transList);
        }

        private void LoadProvider()
        {
            ddlProvider.DataSource = ProviderBLL.GetProviderListForCMB();
            ddlProvider.DataBind();
        }

        private void LoadCategory(string wsLink)
        {
            string ws = regex.Replace(wsLink, "$1");
            if (!ws.EndsWith("?wsdl")) { ws += "?wsdl"; }
            WebServiceInvoker invoker = new WebServiceInvoker(new Uri(ws));

            string methodCategory = regex.Replace(wsLink, "$3");
            ddlCategory.DataSource = invoker.InvokeMethod<DataTable>(invoker.AvailableServices[0], methodCategory, String.Empty);
            ddlCategory.DataBind();
        }

        private void LoadProduct(string wsLink, string categoryID)
        {
            string ws = regex.Replace(wsLink, "$1");
            if (!ws.EndsWith("?wsdl")) { ws += "?wsdl"; }
            WebServiceInvoker invoker = new WebServiceInvoker(new Uri(ws));

            string methodProduct = regex.Replace(wsLink, "$3");
            DataTable dt = invoker.InvokeMethod<DataTable>(invoker.AvailableServices[0], methodProduct, categoryID);
            dtgProduct.DataSource = dt;
            dtgProduct.DataBind();

            btnRegisterTrans.Visible = dt.Rows.Count > 0;
        }

        private void RegisterTrans(string wsLink, List<TransactionENT> transList)
        {
            string ws = regex.Replace(wsLink, "$1");
            if (!ws.EndsWith("?wsdl")) { ws += "?wsdl"; }
            WebServiceInvoker invoker = new WebServiceInvoker(new Uri(ws));

            string methodName = regex.Replace(wsLink, "$3");
            TransactionBLL transBLL = new TransactionBLL();
            bool hasError = false;
            foreach (TransactionENT trans in transList)
            {
                object[] obj = { 
                                   Global.ProviderSID, trans.TransID, trans.ProductID, trans.MinQuantity, 
                                   trans.NextTransQuantity, trans.BeginTransDate, trans.EndTransDate 
                               };
                string result = invoker.InvokeMethod<string>(invoker.AvailableServices[0], methodName, obj);
                if (result == "0")
                {
                    transBLL.InsertTransaction(trans);
                }
                else
                {
                    hasError = true;
                }
            }

            if (hasError)
            {
                lblMessage.Text = "Một số giao dịch đăng ký không thành công.";
                message.Attributes.Add("class", "notification error png_bg message");
            }
            else
            {
                lblMessage.Text = "Giao dịch đăng ký thành công.";
                message.Attributes.Add("class", "notification success png_bg message");
            }
            message.Style["display"] = "block";
        }
    }
}